import createDomElement from './createDomElement';
import mountElement from './mountElement';
import unmountNode from './unmountNode';
import updateNodeElement from './updateNodeElement';
import updateTextNode from './updateTextNode';

export default function diff (virtualDOM, container, oldDOM) {

    const oldVirtualDOM = oldDOM && oldDOM._virtualDOM;
    const oldComponent = oldVirtualDOM && oldVirtualDOM.component;

    // 判断oldDOM是否存在
    if (!oldDOM) {
        mountElement(virtualDOM, container);
    } else if (virtualDOM.type !== oldVirtualDOM.type && typeof virtualDOM.type !== 'function') {
        const newElement = createDomElement(virtualDOM);
        oldDOM.parentNode.replaceChild(newElement, oldDOM);
    } else if (typeof virtualDOM.type === 'function') {
        diffComponent(virtualDOM, oldComponent, oldDOM, container);
    } else if (oldVirtualDOM && virtualDOM.type === oldVirtualDOM.type) {
        if (virtualDOM.type === 'text') {
            // 更新文本内容
            updateTextNode(virtualDOM, oldVirtualDOM, oldDOM);
        } else {
            // 更新元素属性
            updateNodeElement(oldDOM, virtualDOM, oldVirtualDOM);
        }
        // 对比子节点
        virtualDOM.children.forEach((child, index) => {
            diff(child, oldDOM, oldDOM.childNodes[index]);
        });

        let oldChildNodes = oldDOM.childNodes; // 获取旧节点
        if (oldChildNodes.length > virtualDOM.children.length) {
            for (let i = oldChildNodes.length; i >=virtualDOM.children.length; i-- ) {
                unmountNode(oldChildNodes[i]);
            }
        }
    }
};